package com.atguigu.tingshu.order.interceptor.impl;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author  王东剑
 * Created on 23/6/2024 PM12:27
 * Package_name com.atguigu.tingshu.order.interceptor.impl
 * Description
 */
@Service
@Slf4j
public class OrderRepeatSubmitValidOrderHandlerInterceptor implements OrderHandlerInterceptor {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Override
	public OrderInfoVo submitOrderRequestProcess(OrderInfoVo orderInfoVo) {
		String tradeNo = orderInfoVo.getTradeNo();
		log.info("OrderRepeatSubmitValidOrderHandlerInterceptor.submitOrderRequestProcess");
		String script = """
				if (redis.call('exists',KEYS[1]))
				then
				    return redis.call('del',KEYS[1])
				else
				    return 0
				end
				""";
		Long executed = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), List.of(RedisConstant.getOrderRepeatValid(tradeNo)));
		if (executed==0)
			throw new GuiguException(ResultCodeEnum.ORDER_SUBMIT_REPEAT);
		log.info("表单重复提交问题校验通过..........");
		return orderInfoVo;
	}

	@Override
	public int sort() {
		return 2;
	}
}
